package com.CmJava.serviceImpl;

import com.CmJava.entity.Message;
import com.CmJava.entity.MessageList;
import com.CmJava.service.JwtService;
import com.CmJava.service.MessageService;
import com.alibaba.dubbo.config.annotation.Service;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;

import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.List;

@Service
public class JwtServiceImpl implements JwtService {

    @Autowired
    private RedisTemplate redisTemplate;


    @Override
    public boolean compareJwt(String userName, String token) {
        if (redisTemplate.hasKey("ChatRoomLogin")) {
            HashMap map = (HashMap<String, String>) redisTemplate.opsForValue().get("ChatRoomLogin");
            String token0 = (String) map.get(userName);
            if (token.equals(token0)) {
                return true;
            } else {
                return false;
            }
        }
        return false;
    }

    @Override
    public void loginFirst(String userName, String token) {
        //登录完就存在redis
        HashMap<String, String> map = null;
        if (redisTemplate.hasKey("ChatRoomLogin")) {
            map = (HashMap<String, String>) redisTemplate.opsForValue().get("ChatRoomLogin");
            if (map.containsKey(userName)) {
                //已经被登陆了，token覆盖，进行单点登录
                map.remove(userName);
            }
            map.put(userName, token);
        } else {
            map = new HashMap<>();
            map.put(userName, token);
        }
        redisTemplate.opsForValue().set("ChatRoomLogin", map);
    }

    @Override
    public void logout(String userName) {
        if (redisTemplate.hasKey("ChatRoomLogin")) {
            HashMap map = (HashMap<String, String>) redisTemplate.opsForValue().get("ChatRoomLogin");
            map.remove(userName);
            redisTemplate.opsForValue().set("ChatRoomLogin", map);
        }
    }

    @Override
    public String getJwt(String userName) {
        if (redisTemplate.hasKey("ChatRoomLogin")) {
            HashMap map = (HashMap<String, String>) redisTemplate.opsForValue().get("ChatRoomLogin");
            String token = (String) map.get(userName);
            return token;
        }
        return null;
    }
}
